package fr.univ_tln.inf9.exaplanning.api.cours;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.swing.event.EventListenerList;

import fr.univ_tln.inf9.exaplanning.api.composante.TrainingPath;
import fr.univ_tln.inf9.exaplanning.api.cours.event.nameChangedEvent;
import fr.univ_tln.inf9.exaplanning.api.cours.event.nameListener;
import fr.univ_tln.inf9.exaplanning.api.cours.event.typeChangedEvent;
import fr.univ_tln.inf9.exaplanning.api.cours.event.typeListener;
import fr.univ_tln.inf9.exaplanning.api.db.AbstractEntity;
import fr.univ_tln.inf9.exaplanning.api.db.EntityInfo;
import fr.univ_tln.inf9.exaplanning.api.db.SessionManager;
/**
 * 
 * @author ventura
 * @author emilien (persistance)
 *
 */
@EntityInfo(	collections = { },
				key = "name",
				methods = { "getName", "getType" },
				rows = { "course_name", "typec" },
				table = "course",
				variables = { "type" }) 
public class Course extends AbstractEntity {

		private final String name;
		public enum Type {core_curriculum,option};
		private Type type;
		/**
		 * @param name
		 * @param type
		 */
		private EventListenerList listeners;
		
		public Course(String name, Type type) throws IOException, SQLException {
			super(true);
			this.name = name;
			this.type = type;
		}
		
		private Course(String name, String type) throws IOException, SQLException {
			super(false);
			this.name = name;
			this.type = Type.valueOf(type);
		}
		/**
		 * @return the name
		 */
		public String getName() {
			return name;
		}
		
		/**
		 * @return the type
		 */
		public Type getType() {
			return type;
		}
		/**
		 * @param type the type to set
		 */
		public void setType(Type type) {
			this.type = type;
			fireObjectChanged();
			fireTypeChanged();
		}
		
		private void fireTypeChanged() {
			typeListener[] listenerList = (typeListener[])listeners.getListeners(typeListener.class);
			
			for(typeListener listener : listenerList){
				listener.typeChanged(new typeChangedEvent(this, getType()));
			}	
		}
		
		public void addTypeListener(typeListener listener){
			listeners.add(typeListener.class, listener);
		}
		
		public void removeTypeListener(typeListener l){
			 listeners.remove(typeListener.class, l);
		}
		/* (non-Javadoc)
		 * @see java.lang.Object#toString()
		 */
		@Override
		public String toString() {
			return "Matiere [nom=" + name + ", type=" + type + "]";
		}
		
		public static Course findByKey(String key) throws IOException, SQLException {
        	List<List<String>> data = SessionManager.getInstance().getData(Course.class, key);
        	
        	List<String> variables = data.get(0);
        	Course result = new Course(variables.get(0), variables.get(1));
        	
        	return result;
		}
		
}
